﻿using System;
using System.Text;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core.CommonFilter;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Report;
using Kingdee.BOS.Core.SqlBuilder;
using Kingdee.BOS.Model.ReportFilter;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceFacade;
using Kingdee.BOS.ServiceFacade.KDServiceFx;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.WebApi.ServicesStub;

namespace Caraya.MFG.BusinessPlugIn
{
    /// <summary>
    /// WebAPI自定义接口获取报表数据
    /// 知识点：过滤方案
    /// https://vip.kingdee.com/article/25709?productLineId=1
    /// </summary>
    public class ApiStockDetail : AbstractWebApiBusinessService
    {
        public ApiStockDetail(KDServiceContext context) : base(context)
        {
        }

        private DynamicObject GetMATERIAL(int mid)
        {
            var ctx = this.KDContext.Session.AppContext;
            var data1 = LoadBDFullObject("BD_MATERIAL", mid);
            return data1;
        }

        /// <summary>
        /// 根据基础资料的编码，加载基础资料数据包
        /// 有修改（根据主键）
        /// </summary>
        /// <param name="formId"></param>
        /// <param name="number"></param>
        /// <returns></returns>
        private DynamicObject LoadBDFullObject(string formId, object number)
        {
            var ctx = this.KDContext.Session.AppContext;
            FormMetadata meta = MetaDataServiceHelper.Load(ctx, formId) as FormMetadata;
            var queryParam = new QueryBuilderParemeter();
            queryParam.FormId = formId;
            queryParam.BusinessInfo = meta.BusinessInfo;
            queryParam.FilterClauseWihtKey = string.Format(" {0} = '{1}' ", meta.BusinessInfo.GetForm().MasterPKFieldName, number);
            var bdObjs = BusinessDataServiceHelper.Load(ctx, meta.BusinessInfo.GetDynamicObjectType(), queryParam);
            return bdObjs[0];
        }

        //DynamicObject LoadBDFieldObject(string fieldKey, string number)
        //{
        //    BaseDataField bdField = this.View.BillBusinessInfo.GetField(fieldKey) as BaseDataField;        // 构建查询参数，设置过滤条件
        //    QueryBuilderParemeter queryParam = new QueryBuilderParemeter(); 
        //    queryParam.FormId = bdField.LookUpObject.FormId; 
        //    queryParam.FilterClauseWihtKey = string.Format(" {0} = '{1}' ", bdField.NumberProperty.Key, number); 
        //    var bdObjs = BusinessDataServiceHelper.Load(this.Context, bdField.RefFormDynamicObjectType, queryParam);

        //    return bdObjs[0];
        //}

        /// <summary>
        /// https://vip.kingdee.com/article/25709?productLineId=1
        /// </summary>
        /// <returns></returns>
        public string Query(int MATERIALID)
        {
            var ctx = this.KDContext.Session.AppContext;
            ISysReportService sysReporSservice = ServiceFactory.GetSysReportService(ctx);
            var filterMetadata = FormMetaDataCache.GetCachedFilterMetaData(ctx);//加载字段比较条件元数据。
            var reportMetadata = FormMetaDataCache.GetCachedFormMetaData(ctx, "STK_StockDetailRpt");//加载物料收发明细表
            var reportFilterMetadata = FormMetaDataCache.GetCachedFormMetaData(ctx, "STK_StockDetailFilter");//加载物料收发明细表表过滤条件元数据。
            var reportFilterServiceProvider = reportFilterMetadata.BusinessInfo.GetForm().GetFormServiceProvider();
            var model = new SysReportFilterModel();
            model.SetContext(ctx, reportFilterMetadata.BusinessInfo, reportFilterServiceProvider);
            model.FormId = reportFilterMetadata.BusinessInfo.GetForm().Id;
            model.FilterObject.FilterMetaData = filterMetadata;
            model.InitFieldList(reportMetadata, reportFilterMetadata);
            model.GetSchemeList();//过滤方案的主键值，可通过该SQL语句查询得到：SELECT * FROM T_BAS_FILTERSCHEME where FFORMID ='STK_StockDetailRpt' 
            var entity = model.Load("43ac27ab0b2041bcb181962bb119cb6f");//43ac27ab0b2041bcb181962bb119cb6f 62db7daabeacac
            var filter = model.GetFilterParameter();

            var cus = filter.CustomFilter;
            cus["StockOrgId"] = 1;
            cus["BeginDate"] = DateTime.Today.AddYears(-1);
            cus["EndDate"] = DateTime.Today.AddMonths(1);
            if (MATERIALID != 0)
            {
                var MATERIALID_object = GetMATERIAL(MATERIALID);
                cus["BeginMaterialId_Id"] = MATERIALID;
                cus["BeginMaterialId"] = MATERIALID_object;
                cus["EndMaterialId_Id"] = MATERIALID;
                cus["EndMaterialId"] = MATERIALID_object;
            }

            var filter1 = new FilterParameter();
            filter1.CustomFilter = cus;

            IRptParams p = new RptParams();
            p.FormId = reportFilterMetadata.BusinessInfo.GetForm().Id;
            p.StartRow = 1;
            p.EndRow = int.MaxValue;//StartRow和EndRow是报表数据分页的起始行数和截至行数，一般取所有数据，所以EndRow取int最大值。
            p.FilterParameter = filter1;
            p.FilterFieldInfo = model.FilterFieldInfo;

            //加上自定义参数
            p.CustomParams.Add("OpenParameter", "");
            MoveReportServiceParameter param = new MoveReportServiceParameter(ctx, reportMetadata.BusinessInfo, Guid.NewGuid().ToString(), p);
            var rpt = sysReporSservice.GetReportData(param);
            SerializerProxy serialHelper = new SerializerProxy(MessageFormats.Json, UTF8Encoding.UTF8, false, "", true);
            var str = serialHelper.Serialize(rpt.DataSource);
            return str;
        }
    }
}
